import os
import struct
import argparse
import random
# Form implementation generated from reading ui file '.\project.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
import sys
from collections import Counter
from datetime import time

import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from PyQt5 import QtCore, QtGui, QtWidgets
from absl.testing.absltest import _open

from models.experimental import attempt_load
from utils.augmentations import letterbox
from utils.general import check_img_size, non_max_suppression, scale_coords
from utils.plots2 import plot_one_box2
from utils.torch_utils import select_device

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from mainwindow import Ui_MainWindow
import socket
import binascii

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.111.158', 6666))

start_msg_end = 'WHUT001'

ID_name = '目标ID：'
ID_num = '数量：'


class UiMain(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super(UiMain, self).__init__()
        self.timer_video = QtCore.QTimer()  # 创建定时器
        self.time_quit = QtCore.QTimer()
        self.timelunshu = QtCore.QTimer()
        self.setupUi(self)
        self.cap = cv2.VideoCapture(0)
        self.init_slots()
        self.cap.set(cv2.CAP_PROP_EXPOSURE, 50)
        self.PrepParameters()
        self.status0()
        self.timerimg = QtCore.QTimer()
        self.next.hide()
        self.model_init()

    def from_code_to_tcp(self, weather_start_or_end, msg_data):
        if weather_start_or_end == 0:  # 代表是开始，要发0
            tcp_head = '00 00 00 00 00 00 00 '
            num = str(len(msg_data))
            if len(msg_data) >= 16:
                gg = hex(len(msg_data)).lstrip('0x')
            else:
                gg = '0' + num
            tcp_head = tcp_head + gg
            start_msg_end_hex = ''
            for i in range(len(msg_data)):
                start_msg_end_hex = start_msg_end_hex + hex(ord(msg_data[i]))[2:] + ''
            start_msg = bytes.fromhex(tcp_head)
            start_msg = start_msg + bytes.fromhex(start_msg_end_hex)
            # print(start_msg)
            client.send(start_msg)
        elif weather_start_or_end == 1:  # 代表要结束，发1
            tcp_head = '00 00 00 01 00 00 00 '
            end_str = 'END'
            num = str(len(msg_data) + 3)
            if len(msg_data) + 3 >= 16:
                gg = hex(len(msg_data) + 3).lstrip('0x')
            else:
                gg = '0' + num
            tcp_head = tcp_head + gg
            print(tcp_head)
            end_msg = bytes.fromhex(tcp_head)
            end_msg_end_hex = ''
            str_split = msg_data.split('#')
            for i in range(msg_data.count('#')):
                for j in range(len(str_split[i])):
                    end_msg_end_hex = end_msg_end_hex + hex(ord((str_split[i])[j]))[2:] + ''

                end_msg_end_hex = end_msg_end_hex + ' 0D'
            for i in range(len(end_str)):
                end_msg_end_hex = end_msg_end_hex + hex(ord(end_str[i]))[2:] + ''
            end_msg = end_msg + bytes.fromhex(end_msg_end_hex)
            client.send(end_msg)
        elif weather_start_or_end == 3:  # 要发3
            tcp_head = '00 00 00 03 00 00 00 '
            num = str(len(msg_data))
            if len(msg_data) >= 16:
                gg = hex(len(msg_data)).lstrip('0x')
            else:
                gg = '0' + num
            tcp_head = tcp_head + gg
            start_msg_end_hex = ''
            for i in range(len(msg_data)):
                start_msg_end_hex = start_msg_end_hex + hex(ord(msg_data[i]))[2:] + ''
            start_msg = bytes.fromhex(tcp_head)
            start_msg = start_msg + bytes.fromhex(start_msg_end_hex)
            # print(start_msg)
            client.send(start_msg)

    def status0(self):

        self.status_tetx.clear()
        self.status_tetx.setText('                  空闲')

    def nexthide(self):
        self.next.hide()

    # 加载相关参数，并初始化模型
    def model_init(self):
        # 模型相关参数配置
        parser = argparse.ArgumentParser()
        parser.add_argument('--weights', nargs='+', type=str,
                            default=r'best123.pt', help='model.pt path(s)')
        # file/folder, 0 for webcam
        parser.add_argument('--source', type=str,
                            default='0', help='source')
        parser.add_argument('--img-size', type=int,
                            default=640, help='inference size (pixels)')
        parser.add_argument('--conf-thres', type=float,
                            default=0.7, help='object confidence threshold')
        parser.add_argument('--iou-thres', type=float,
                            default=0.45, help='IOU threshold for NMS')
        parser.add_argument('--device', default='0',
                            help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
        parser.add_argument(
            '--view-img', action='store_true', help='display results')
        parser.add_argument('--save-txt', action='store_true',
                            help='save results to *.txt')
        parser.add_argument('--save-conf', action='store_true',
                            help='save confidences in --save-txt labels')
        parser.add_argument('--nosave', action='store_true',
                            help='do not save images/videos')
        parser.add_argument('--classes', nargs='+', type=int,
                            help='filter by class: --class 0, or --class 0 2 3')
        parser.add_argument(
            '--agnostic-nms', action='store_true', help='class-agnostic NMS')
        parser.add_argument('--augment', action='store_true',
                            help='augmented inference')
        parser.add_argument('--update', action='store_true',
                            help='update all models')
        parser.add_argument('--project', default='runs/detect',
                            help='save results to project/name')
        parser.add_argument('--name', default='exp',
                            help='save results to project/name')
        parser.add_argument('--exist-ok', action='store_true',
                            help='existing project/name ok, do not increment')
        self.opt = parser.parse_args()
        print(self.opt)

        source, weights, view_img, save_txt, imgsz = self.opt.source, self.opt.weights, self.opt.view_img, self.opt.save_txt, self.opt.img_size

        self.device = select_device(self.opt.device)
        # # gpu
        self.device = torch.device('cuda:0')

        # 如果只有cpu的话，就改成
        # self.device = torch.device('cpu')

        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        cudnn.benchmark = True

        # Load model
        self.model = attempt_load(
            weights, device=self.device)  # load FP32 model
        stride = int(self.model.stride.max())  # model stride
        self.imgsz = check_img_size(imgsz, s=stride)  # check img_size
        if self.half:
            self.model.half()  # to FP16

        # Get names and colors
        self.names = self.model.module.names if hasattr(
            self.model, 'module') else self.model.names
        self.colors = [[random.randint(0, 255)
                        for _ in range(3)] for _ in self.names]

    def PrepParameters(self):
        self.R = 1
        self.G = 1
        self.B = 1
        self.fps = 0.0
        self.timeF = 2
        self.c = 1
        self.zhi = []
        self.count = 1
        self.panduan = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        self.dict00 = {}
        self.none = 0
        self.which_epoch = 0
        self.lunshu = 1
        self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5 = 0, 0, 0, 0, 0, 0
        self.ii = 0
        self.jj = 0
        self.zhizz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    def init_slots(self):
        self.startbtn.clicked.connect(self.button_camera_open)
        # self.startbtn.clicked.connect(self.model_init)
        self.timer_video.timeout.connect(self.show_video_frame)  # 定时器超时，将槽绑定至show_video_frame
        self.time_quit.timeout.connect(self.stop)
        self.timelunshu.timeout.connect(self.ls)

    # 目标检测
    def detect(self, name_list, img):
        global x1, x2, y1, y2
        global a1, a2, b1, b2
        showimg = img
        with torch.no_grad():
            img = letterbox(img, new_shape=self.opt.img_size)[0]
            # Convert
            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = np.ascontiguousarray(img)
            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.half else img.float()  # uint8 to fp16/32
            img /= 255.0  # 0 - 255 to 0.0 - 1.0
            if img.ndimension() == 3:
                img = img.unsqueeze(0)
            # Inference
            pred = self.model(img, augment=self.opt.augment)[0]
            # Apply NMS
            pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=self.opt.classes,
                                       agnostic=self.opt.agnostic_nms)
            # print(pred)

            # Process detections
            for i, det in enumerate(pred):

                if det is not None and len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], showimg.shape).round()
                    # x1,x2,y1,y2=0,0,0,0
                    for *xyxy, conf, cls in reversed(det):
                        label = '%s %.2f' % (self.names[int(cls)], conf)
                        zuobiao = self.names[int(cls)]
                        # print(self.names[int(cls)])

                        x1, x2, y1, y2, a1, a2, b1, b2 = plot_one_box2(xyxy, zuobiao, showimg, label=label,
                                                                       color=self.colors[int(cls)],
                                                                       line_thickness=2)
                        # print(x1)
                        # print(a1)
                        if x1 - 15 < a1 < a2 < x2 + 15 and 110 < b1 < b2 < y2 and self.names[int(cls)] != "desk":
                            name_list.append(self.names[int(cls)])
                            print(name_list)
                        a1, a2, b1, b2 = 0, 0, 0, 0

    def pyqt_append(self, dict00):
        lst00 = list(dict00.keys())
        print(lst00)
        flag = 0
        for i in dict00.values():
            print(i)
            if i > 1:
                flag = 1
        print(flag)
        if flag == 0:
            for i in range(len(lst00)):
                self.output_text.append(ID_name + lst00[i] + '       ' + ID_num + '1')
                self.timer_video.stop()

        elif flag == 1:
            for i in range(len(lst00)):
                self.output_text.append(ID_name + list(lst00)[i] + '       ' + ID_num + str(dict00[list(lst00)[i]]))
                self.timer_video.stop()

    def pyqt_append2(self, msg_list):
        set_msg_list = set(msg_list)
        if len(set_msg_list) == len(msg_list):
            for i in range(len(msg_list)):
                self.output_text.append(ID_name + msg_list[i] + '       ' + ID_num + '1')
        # self.timer_video.stop()
        else:
            dict_list = dict(Counter(msg_list))
            for i in range(len(set_msg_list)):
                self.output_text.append(
                    ID_name + list(set_msg_list)[i] + '       ' + ID_num + str(dict_list[list(set_msg_list)[i]]))

    def msg_append(self, dict00):  # 向裁判软件发送信息
        lst00 = list(dict00.keys())
        print(lst00)
        result_file = open(r"/home/jetson/Desktop/result.txt", "w")
        result_file.write("START\n")
        flag = 0
        for i in dict00.values():
            print(i)
            if i > 1:
                flag = 1
        print(flag)
        if flag == 0:  # 如果没有重复的物体
            self.tcp_msg = 'START#'
            for i in range(len(lst00)):
                self.tcp_msg = self.tcp_msg + 'Goal_ID=' + lst00[i] + ';Num=' + '1#'
                file_str = "Goal_ID=" + lst00[i] + ";Num=1\n"
                result_file.write(file_str)
            # self.tcp_msg=self.tcp_msg+'END'
            result_file.write("END")
            result_file.close()
            # self.from_code_to_tcp(1, self.tcp_msg)
            print('开始传输')
            while (1):
                exist = os.path.exists(r"/home/jetson/Desktop/result.txt")  # 判断是否存在result.txt文件
                print('正在判断。。。')
                if exist == 1:
                    print('存在此文件')
                    size = os.path.getsize(r"/home/jetson/Desktop/result.txt")  # 得到要传输的文件所要的数据包大小
                    print(size)
                    tx = struct.pack('!ii', 1, size)  # 定义包头 和 数据包大小
                    print(tx)
                    # time.sleep(1)
                    client.sendall(tx)  # 发送自定义数据包头和数据包大小
                    filepath = r"/home/jetson/Desktop/result.txt"  # 要发送的文件路径
                    filedata = open(filepath, 'r', encoding='gb18030').read()  # 读取文件
                    print(filedata)
                    b = filedata.encode()
                    print(b)

                    filepath_arr = filepath.split('/')  # 切片数据
                    print(filepath_arr)
                    filename = filepath_arr[len(filepath_arr) - 1]
                    print(filename)

                    client.sendall(b)  # 发送数据
                    # time.sleep(1)
                    print('DONE')
                    break

            self.status_tetx.clear()
            self.status_tetx.setPlainText('               结束')
            # print(self.tcp_msg)
            self.timer_video.stop()

        elif flag == 1:  # 如果有重复的物体
            self.tcp_msg = 'START#'
            for i in range(len(lst00)):
                self.tcp_msg = self.tcp_msg + 'Goal_ID=' + list(lst00)[i] + ';Num=' + str(
                    dict00[list(lst00)[i]]) + '#'
                file_str = "Goal_ID=" + list(lst00)[i] + ";Num=" + str(dict00[list(lst00)[i]]) + "\n"
                result_file.write(file_str)
            # self.tcp_msg=self.tcp_msg+'END'
            result_file.write("END")
            result_file.close()
            # self.from_code_to_tcp(1, self.tcp_msg)

            print('开始传输')
            while (1):
                exist = os.path.exists(r"/home/jetson/Desktop/result.txt")  # 判断是否存在result.txt文件
                print('正在判断。。。')
                if exist == 1:
                    print('存在此文件')
                    size = os.path.getsize(r"/home/jetson/Desktop/result.txt")  # 得到要传输的文件所要的数据包大小
                    print(size)
                    tx = struct.pack('!ii', 1, size)  # 定义包头 和 数据包大小
                    print(tx)
                    # time.sleep(1)
                    client.sendall(tx)  # 发送自定义数据包头和数据包大小
                    filepath = r"/home/jetson/Desktop/result.txt"  # 要发送的文件路径
                    filedata = open(filepath, 'r', encoding='gb18030').read()  # 读取文件
                    print(filedata)
                    b = filedata.encode()
                    print(b)

                    filepath_arr = filepath.split('/')  # 切片数据
                    print(filepath_arr)
                    filename = filepath_arr[len(filepath_arr) - 1]
                    print(filename)

                    client.sendall(b)  # 发送数据
                    # time.sleep(1)
                    print('DONE')
                    break

            self.status_tetx.clear()
            self.status_tetx.setPlainText('                  结束')
            print(self.tcp_msg)
            self.timer_video.stop()

    def msg_append2(self, msg_list):  # 向裁判软件发送信息
        set_msg_list = set(msg_list)
        result_file = open(r"/home/jetson/Desktop/result.txt", "w")
        result_file.write("START\n")
        if len(set_msg_list) == len(msg_list):  # 如果没有重复的物体
            self.tcp_msg = 'START#'
            for i in range(len(msg_list)):
                self.tcp_msg = self.tcp_msg + 'Goal_ID=' + msg_list[i] + ';Num=' + '1#'
                file_str = "Goal_ID=" + msg_list[i] + ";Num=1\n"
                result_file.write(file_str)
            # self.tcp_msg=self.tcp_msg+'END'
            result_file.write("END")
            result_file.close()
            self.from_code_to_tcp(1, self.tcp_msg)
            self.status_tetx.clear()
            self.status_tetx.setPlainText('               结束')
            print(self.tcp_msg)
            self.timer_video.stop()

        else:  # 如果有重复的物体
            dict_list = dict(Counter(msg_list))
            self.tcp_msg = 'START#'
            for i in range(len(set_msg_list)):
                self.tcp_msg = self.tcp_msg + 'Goal_ID=' + list(set_msg_list)[i] + ';Num=' + str(
                    dict_list[list(set_msg_list)[i]]) + '#'
                file_str = "Goal_ID=" + list(set_msg_list)[i] + ";Num=" + str(dict_list[list(set_msg_list)[i]]) + "\n"
                result_file.write(file_str)
            # self.tcp_msg=self.tcp_msg+'END'
            result_file.write("END")
            result_file.close()
            self.from_code_to_tcp(1, self.tcp_msg)
            self.status_tetx.clear()
            self.status_tetx.setPlainText('                  结束')
            print(self.tcp_msg)
            self.timer_video.stop()

    def stop(self):
        self.output_text.clear()
        self.msg_append2(self.name_list)
        self.pyqt_append2(self.name_list)
        self.status_tetx.setPlainText('             结束')
        self.timer_video.stop()
        self.time_quit.stop()

    # 打开摄像头检测
    def button_camera_open(self):

        # 设置使用的摄像头序号，系统自带为0
        # camera_num = 0
        # 打开摄像头
        # self.cap = cv2.VideoCapture(camera_num)
        # 判断摄像头是否处于打开状态
        bool_open = self.cap.isOpened()
        if not bool_open:
            QtWidgets.QMessageBox.warning(self, u"Warning", u"打开摄像头失败", buttons=QtWidgets.QMessageBox.Ok,
                                          defaultButton=QtWidgets.QMessageBox.Ok)
        else:

            self.from_code_to_tcp(0, start_msg_end)
            self.status_tetx.setPlainText('             识别中')
            self.timer_video.start(30)
            self.time_quit.start(145000)

    def ls(self):
        if self.which_epoch == 0:
            self.status_tetx.clear()
            self.status_tetx.setPlainText('            转动中')
            print('rotate')
            self.from_code_to_tcp(3, '0000')
            self.next.show()
            self.timerimg.start(5000)
            self.dict11 = self.name_list
            self.lunshu=1
            self.which_epoch += 1
            self.c=-20
            self.timelunshu.stop()
            self.count=1
            self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5 = 0, 0, 0, 0, 0, 0
            self.ii = 0
            self.jj = 0
            self.zhizz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            self.timer_video.start(30)
        elif self.which_epoch == 1:
            self.status_tetx.clear()
            self.status_tetx.setPlainText('            转动中')
            print('rotate')
            self.from_code_to_tcp(3, '0000')
            self.next.show()
            self.timerimg.start(5000)
            self.dict22 = self.name_list
            self.lunshu=1
            self.which_epoch += 1
            self.c=-20
            self.timelunshu.stop()
            self.count=1
            self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5 = 0, 0, 0, 0, 0, 0
            self.ii = 0
            self.jj = 0
            self.zhizz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            self.timer_video.start(30)
        else:
            self.dict33 = self.name_list
            self.Dict11, self.Dict22, self.Dict33 = Counter(self.dict11), Counter(self.dict22), Counter(
                self.dict33)
            self.dict00 = dict(self.Dict11 + self.Dict22 + self.Dict33)
            print(self.dict00)

            # 输出结果
            self.output_text.clear()
            self.msg_append(self.dict00)
            self.pyqt_append(self.dict00)

            self.timer_video.stop()
            self.time_quit.stop()
            self.timelunshu.stop()

    # 定义视频帧显示操作
    def show_video_frame(self):
        self.status_tetx.setPlainText('             识别中')
        self.name_list = []
        flag, img = self.cap.read()

        if img is not None:
            self.detect(self.name_list, img)

            show = cv2.resize(img, (640, 480))  # 直接将原始img上的检测结果进行显示
            self.result = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
            self.showImage = QtGui.QImage(self.result.data, self.result.shape[1], self.result.shape[0],
                                          QtGui.QImage.Format_RGB888)

            if self.showImage:
                self.image_show_label.setPixmap(QtGui.QPixmap.fromImage(self.showImage))
                self.image_show_label.setScaledContents(True)  # 设置图像自适应界面大小

                self.output_text.clear()
                self.pyqt_append2(self.name_list)

            if self.lunshu==1:
                self.timelunshu.start(10000)  #计数器
                self.lunshu+=1

            if len(self.name_list) != 0:
                self.c += 1
                print("c")
                print(self.c)
                if (self.c % self.timeF == 0) and self.c > 0:
                    print(self.c)

                    # name_list转为字典，每一个类别计数
                    value = self.name_list
                    print(value)
                    CA001, CA002, CA003, CA004, CB001, CB002, CB003, CB004, CC001, CC002, CC003, CC004, CD001, CD002, CD003, CD004, W001, W002, W003, W004 = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                    for i in value:
                        if i == "CA001":
                            CA001 += 1
                        elif i == "CA002":
                            CA002 += 1
                        elif i == "CA003":
                            CA003 += 1
                        elif i == "CA004":
                            CA004 += 1
                        elif i == "CB001":
                            CB001 += 1
                        elif i == "CB002":
                            CB002 += 1
                        elif i == "CB003":
                            CB003 += 1
                        elif i == "CB004":
                            CB004 += 1
                        elif i == "CC001":
                            CC001 += 1
                        elif i == "CC002":
                            CC002 += 1
                        elif i == "CC003":
                            CC003 += 1
                        elif i == "CC004":
                            CC004 += 1
                        elif i == "CD001":
                            CD001 += 1
                        elif i == "CD002":
                            CD002 += 1
                        elif i == "CD003":
                            CD003 += 1
                        elif i == "CD004":
                            CD004 += 1
                        elif i == "W001":
                            W001 += 1
                        elif i == "W002":
                            W002 += 1
                        elif i == "W003":
                            W003 += 1
                        elif i == "W004":
                            W004 += 1
                        else:
                            self.none = 1
                    if not self.none:
                        if self.count == 1:
                            dict1 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            global lst1
                            lst1 = list(dict1.values())
                            print(lst1)
                            self.zhi.append(lst1)
                            # print(self.zhi)
                        elif self.count == 2:
                            dict2 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst2 = list(dict2.values())
                            self.zhi.append(lst2)
                            # print(self.zhi)
                        elif self.count == 3:
                            dict3 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst3 = list(dict3.values())
                            self.zhi.append(lst3)
                            # print(self.zhi)
                        elif self.count == 4:
                            dict4 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst4 = list(dict4.values())
                            self.zhi.append(lst4)
                            # print(self.zhi)
                        elif self.count == 5:
                            dict5 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst5 = list(dict5.values())
                            self.zhi.append(lst5)
                            # print(self.zhi)
                        elif self.count == 6:
                            dict6 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst6 = list(dict6.values())
                            self.zhi.append(lst6)
                            # print(self.zhi)
                        elif self.count == 7:
                            dict7 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst7 = list(dict7.values())
                            self.zhi.append(lst7)
                            # print(self.zhi)
                        elif self.count == 8:
                            dict8 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst8 = list(dict8.values())
                            self.zhi.append(lst8)
                            # print(self.zhi)
                        elif self.count == 9:
                            dict9 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                     "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                     "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                     "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                     "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst9 = list(dict9.values())
                            self.zhi.append(lst9)
                            # print(self.zhi)
                        elif self.count == 10:
                            dict10 = {"CA001": CA001, "CA002": CA002, "CA003": CA003, "CA004": CA004,
                                      "CB001": CB001, "CB002": CB002, "CB003": CB003, "CB004": CB004,
                                      "CC001": CC001, "CC002": CC002, "CC003": CC003, "CC004": CC004,
                                      "CD001": CD001, "CD002": CD002, "CD003": CD003, "CD004": CD004,
                                      "W001": W001, "W002": W002, "W003": W003, "W004": W004}
                            lst10 = list(dict10.values())
                            self.zhi.append(lst10)
                            # print(self.zhi)
                        self.none = 0

                        self.count = self.count + 1
                        print("count")
                        print(self.count)

                if self.count == 11:
                    self.timelunshu.stop()

                    for i in range(0, 10):
                        for j in range(0, 20):
                            if self.zhi[i][j] != 0:
                                self.panduan[j] += 1
                    print(self.panduan)

                    for i in range(0, 20):
                        for j in range(0, 10):
                            if self.panduan[i] < 5 and self.panduan[i] > 0:
                                self.zhi[j][i] = 0

                    print(self.zhi)

                    #输出出现数量最多的数
                    for i in range(0, 20):
                        for j in range(0, 10):  # gai!
                            if self.zhi[j][i] == 0:
                                self.zhic0 += 1  # self.zhic0赋初值0
                            if self.zhi[j][i] == 1:
                                self.zhic1 += 1
                            if self.zhi[j][i] == 2:
                                self.zhic2 += 1
                            if self.zhi[j][i] == 3:
                                self.zhic3 += 1
                            if self.zhi[j][i] == 4:
                                self.zhic4 += 1
                            if self.zhi[j][i] == 5:
                                self.zhic5 += 1

                        self.zhicc = [self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5]
                        # print("zhicc", self.zhicc)
                        self.zhicount = [0, 1, 2, 3, 4, 5]

                        for k in self.zhicc:
                            if k > self.zhizz[self.ii]:
                                # print("大于")
                                self.zhizz[self.ii] = self.zhicount[self.jj]
                            self.jj += 1

                        self.ii += 1
                        self.jj = 0
                        self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5 = 0, 0, 0, 0, 0, 0

                    print(self.zhizz)
                    lst0 = ["CA001", "CA002", "CA003", "CA004", "CB001", "CB002", "CB003", "CB004",
                            "CC001", "CC002", "CC003", "CC004", "CD001", "CD002", "CD003", "CD004",
                            "W001", "W002", "W003", "W004"]
                    dict0 = dict(zip(lst0, self.zhizz))
                    print(dict0)

                    self.dict00 = {key: value for key, value in dict0.items() if value != 0}
                    print(self.dict00)

                    if self.which_epoch == 0:
                        self.dict11 = self.dict00
                        self.status_tetx.clear()
                        self.status_tetx.setPlainText('            转动中')
                        print('rotate1')
                        self.from_code_to_tcp(3, '0000')
                        self.next.show()
                        self.timerimg.start(5000)
                        self.count = 0
                        # 控制转动时间

                        self.c = -20

                        self.panduan = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        self.zhi = []
                        value = 0
                        lst1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst4 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst5 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst6 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst7 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst8 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst10 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        dict0 = {}
                        self.dict00 = {}
                        self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5 = 0, 0, 0, 0, 0, 0
                        self.ii = 0
                        self.jj = 0
                        self.zhizz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        self.status_tetx.setPlainText('            转动中')
                        self.which_epoch = self.which_epoch + 1

                    elif self.which_epoch == 1:
                        self.dict22 = self.dict00
                        self.status_tetx.clear()
                        self.status_tetx.setPlainText('            转动中')
                        print('rotate2')
                        self.from_code_to_tcp(3, '0000')
                        self.next.show()
                        self.timerimg.start(5000)
                        self.count = 0
                        # 控制转动时间
                        self.c = -20
                        self.panduan = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        self.zhi = []
                        value = 0
                        lst1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst4 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst5 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst6 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst7 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst8 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst9 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        lst10 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        dict0 = {}
                        self.dict00 = {}
                        self.zhic0, self.zhic1, self.zhic2, self.zhic3, self.zhic4, self.zhic5 = 0, 0, 0, 0, 0, 0
                        self.ii = 0
                        self.jj = 0
                        self.zhizz = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                        self.status_tetx.setPlainText('            转动中')
                        self.which_epoch = self.which_epoch + 1

                    else:  # 到了最后一次
                        print('rotate3')
                        self.dict33 = self.dict00
                        self.Dict11, self.Dict22, self.Dict33 = Counter(self.dict11), Counter(self.dict22), Counter(
                            self.dict33)
                        self.dict00 = dict(self.Dict11 + self.Dict22 + self.Dict33)
                        print(self.dict00)

                        # 输出结果
                        self.output_text.clear()
                        self.msg_append(self.dict00)
                        self.pyqt_append(self.dict00)

                        self.timer_video.stop()
                        self.time_quit.stop()

        else:
            self.timer_video.stop()
            self.cap.release()
            self.image_show_label.clear()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = UiMain()
    ui.show()
    sys.exit(app.exec_())
